var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var util = require('util');
 var fs = require('fs');
router.use('/', function(req, res) {
 //生成multiparty对象，并配置上传目标路径
 var form = new multiparty.Form({uploadDir: './public/files/'});
 //上传完成后处理
 form.parse(req, function(err, fields, files) {
   var filesTmp = JSON.stringify(files,null,2);

   if(err){
     console.log('parse error: ' + err);
   } else {
     console.log('parse files: ' + filesTmp);
     var inputFile = files.fileDataFileName[0];
     console.log('filesTmp: ' + inputFile);
     var uploadedPath = inputFile.path;
     var uploadedPaths=uploadedPath.replace(/"([^\\]*)"/g,"/")
      console.log(uploadedPaths)
     var dstPath = './public/files/' + inputFile.originalFilename;
     console.log(typeof dstPath)
    //重命名为真实文件名
     fs.rename(uploadedPaths, dstPath, function(err) {
       if(err){
         console.log('rename error: ' + err);
       } else {
         console.log('rename ok');
         var mypath = dstPath.replace("./public","http://localhost"+":3000"); //context.ip是我自己设置的后台的ip名，根据环境，可以是localhost,也可以是电脑ip
          res.send({errno:0,data:[mypath]}) //返回图片路径，让前端展示
       }
     });
   }
   
});
});
module.exports = router;